package com.uvnos4j.matilda.commons.ds.aspect;


import com.uvnos4j.matilda.commons.ds.DynamicDataSourceContextHolder;
import com.uvnos4j.matilda.commons.ds.annotation.Ds;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * 数据源切面处理
 * <p>
 * Description:数据源切面处理
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @since 2020-08-15 01:16:11
 */
@Slf4j
@Aspect
@Order(1)
@Component
public class DsAspect {

    @Pointcut("@annotation(com.uvnos4j.matilda.commons.ds.annotation.Ds) || @within(com.uvnos4j.matilda.commons.ds.annotation.Ds)")
    public void dsPointCut() {
    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Ds ds = getDataSource(point);

        if (ds != null) {
            DynamicDataSourceContextHolder.setDataSourceType(ds.value().name());
        }

        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public Ds getDataSource(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Ds ds = method.getAnnotation(Ds.class);
        if (ds == null) {
            Class<?> targetClass = point.getTarget().getClass();
            ds = targetClass.getAnnotation(Ds.class);
        }
        return ds;
    }
}